var usersModel = require("../models/users");
var jwt = require('jsonwebtoken');
var fs = require('fs')
const Core = require('@alicloud/pop-core');
const config = require('../tools/aliconfig');
//配置
let client = new Core(config.alicloud);
let requestOption = {
  method: 'POST'
}


//手机号码验证
var validatePhoneCode = [];

function rand(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

//模拟验证码发送接口
var sendCode = (req, res) => {
  let phone = req.query.phone;
  if (sendCodeP(phone)) {
    return res.send({
      'code': 400,
      'msg': '已发送过验证码，稍后再发'
    })
  }
  console.log(req.query)
  let code = rand(1000, 9999);
  validatePhoneCode.push({
    'phone': phone,
    'code': code
  })
  res.send({
    'code': 200,
    'msg': '发送成功'
  });
  console.log(code);
}

let sendCodeP = (phone) => {
  for (var item of validatePhoneCode) {
    if (phone == item.phone) {
      return true;
    }
  }
  return false;
}
//验证
let findCodeAndPhone = (phone, code) => {
  for (var item of validatePhoneCode) {
    if (phone == item.phone && code == item.code) {
      return 'login';
    }
  }
  return false;
}
//验证码登录
var codePhoneLogin = async (req, res) => {
  let { phone, code } = req.query;
  //验证手机号是否发送过验证码
  if (sendCodeP(phone)) {
    let status = findCodeAndPhone(phone, code);
    if (status == 'login') {
      //已经登录成功
      //登录成功之后的操作
      // let user = await phoneLoginBind(phone);
      res.send({
        code: 200,
        msg: '登录已成功',
        // data: user[0]
      })
    } else if (status == 'error') {
      res.send({
        'code': 200,
        'msg': '登录失败'
      })
    }
  } else {
    res.send({
      'code': 400,
      'msg': '未发送验证码'
    })
  }
}

var sendCoreCode = (req, res) => {
  let phone = req.query.phone;
  let code = rand(1000, 9999);
  console.log(phone)
  var params = {
    // "RegionId": "cn-hangzhou",
    "PhoneNumbers": phone,
    "SignName": "asdjminq",
    "TemplateCode": "SMS_153055065",
    "TemplateParam": JSON.stringify({ "code": code })
  }
  client.request('SendSms', params, requestOption).then((result) => {
    console.log(result);
    if (result.Code == 'OK') {
      res.send({
        code: 200,
        msg: '发送成功'
      });
      validatePhoneCode.push({
        'phone': phone,
        'code': code
      })
      console.log(code);
    } else {
      res.send({
        code: 400,
        msg: '发送失败'
      })
    }
  })
}

module.exports = {
  sendCode,
  codePhoneLogin,
  sendCoreCode
}

module.exports.register = async function (req, res, next) {
  var data = {
    username: req.body.username,
    password: req.body.password,
    password2: req.body.password2,
  }

  await usersModel.findOne({ username: data.username }, function (err, doc) {
    console.log(doc);
    if (!err) {
      if (doc != null) {
        return res.json({
          data: '已有账号',
          message: "already"
        })
      } else {
        usersModel.create(data, function (err) {
          if (!err) {
            return res.json({
              message: "success",
              data: '注册成功',
            })
          }
          return res.json({
            data: '注册失败',
            message: "err"
          })
        })
      }
    }
  })
}

module.exports.login = (req, res, next) => {
  var userInfo = {
    username: req.body.username,
    password: req.body.password,
  }
  usersModel.find(userInfo, (err, docs) => {
    console.log(docs);
    if (err) {
      res.redirect('/login')
    } else {
      //登陆成功
      if (docs.length > 0) {
        let secretOrPrivateKey = "This is perfect projects.";
        userInfo.token = "bearer " + jwt.sign(userInfo, secretOrPrivateKey, {
          expiresIn: 60 * 60 * 24 * 7 // 一周过期
        });

        res.send({ code: 1, message: '登陆成功', userInfo })
      }
    }
  })
}